package com.zlfund.cat.zjgsmk.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

/**
 * Created by chenjun on 2017/8/18.
 */

public class ListViewAdapter<T> extends BaseAdapter {
    private List<T> mList;
    private Context mContext;
    private IListViewAdapterHelper<T> mAdapterHelper;

    public ListViewAdapter(Context context,IListViewAdapterHelper<T> helper){
        mContext = context;
        mAdapterHelper = helper;
    }

    @Override
    public int getViewTypeCount() {
        return mAdapterHelper.getViewTypeCount();
    }

    @Override
    public int getItemViewType(int position) {
        return mAdapterHelper.getViewTypeAtPosition(position);
    }

    @Override
    public int getCount() {
        return mList == null ? 0 : mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ListViewHolder holder;
        if (convertView == null){
            convertView = createView(position, parent);
            holder = createHolder(convertView, position);
        }else {
            holder = (ListViewHolder) convertView.getTag();
            if (holder.getmType() != getItemViewType(position)){
                convertView = createView(position,parent);
                holder = createHolder(convertView, position);
            }
        }
        mAdapterHelper.initViews(holder,position,mList.get(position));
        return convertView;
    }

    private View createView(int position,ViewGroup parent){
        return LayoutInflater.from(mContext).inflate(mAdapterHelper.getLayoutId(position),parent,false);
    }

    private ListViewHolder createHolder(View convertView,int position){
        ListViewHolder holder = new ListViewHolder(convertView);
        holder.setmType(getItemViewType(position));
        convertView.setTag(holder);
        return holder;
    }

    public void setList(List<T> list){
        mList = list;
        notifyDataSetChanged();
    }
}
